﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Sansar.Register;


namespace BranchOfSansar.Register.Authentication
{
    public partial class frmRegUser : Form
    {
        private User CurrUser = null;
        private bool IsNew = false;

        public frmRegUser()
        {
            InitializeComponent();
            CurrUser = new User() { UserId=0 };
            IsNew = true;
            using (RegisterClient ct = new RegisterClient(Globals.Token))
            {
                cmbPosition.Properties.Items.AddRange(ct.PositionList().Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { Display = s.Name, StrValue = s.PositionNo }).ToArray());
            }

            cmbPosition.SelectedIndex = cmbPosition.Properties.Items.Count > 0 ? 0 : -1;
            cmbStatus.SelectedIndex = 0;
            txtPassword1.Enabled = false;
            txtPassword2.Enabled = false;
        }

        public frmRegUser(User usr) : this()
        {
            CurrUser = usr;
            IsNew = false;
            txtName.Text = usr.Name;
            txtUserNo.Text = usr.UserId.ToString();
            txtUserNo.Enabled = false;
            txtPassword1.Text = usr.Password;
            txtPassword2.Text = usr.Password;
            for (int i = 0; i < cmbPosition.Properties.Items.Count; i++)
            {
                if (((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbPosition.Properties.Items[i]).StrValue == usr.PositionNo)
                {
                    cmbPosition.SelectedItem = i;
                    break;
                }                
            }
            cmbStatus.SelectedIndex = usr.Status ? 1 : 0;
            chkIsAuth.Checked = usr.IsAuthentication;
            BindRoles();
        }

        private void BindRoles()
        {
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient reg = new BranchOfSansar.Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                lstRoles.Items.AddRange(reg.UserRoles(CurrUser.UserId));
            }
        }

        private void frmRegUser_Load(object sender, EventArgs e)
        {
           
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void chkIsAuth_CheckedChanged(object sender, EventArgs e)
        {
            txtPassword1.Enabled = chkIsAuth.Checked;
            txtPassword2.Enabled = chkIsAuth.Checked;

            if (!chkIsAuth.Checked)
            {
                txtPassword1.Text = "";
                txtPassword2.Text = "";
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            using (RegisterClient reg = new RegisterClient(Globals.Token))
            {
                int id = 0;
                Result res;

                if (string.IsNullOrWhiteSpace(txtUserNo.Text))
                {
                    Globals.Warr("Хэрэглэгчийн дугаар хоосон байна!");
                    txtUserNo.Focus();
                    return;
                }
                if (string.IsNullOrWhiteSpace(txtName.Text))
                {
                    Globals.Warr("Хэрэглэгчийн нэр хоосон байна!");
                    txtName.Focus();
                    return;
                }                
                if (chkIsAuth.Checked)
                    if (txtPassword1.Text != txtPassword2.Text)
                    {
                        Globals.Warr("Нууц үг ялгаатай байна");
                        return;
                    }
                int[] roles = lstRoles.Items.Cast<BranchOfSansar.Sansar.Enquiry.ComboItem>().Select(s => s.IntValue).ToArray();

                CurrUser.UserId = int.Parse(txtUserNo.Text);
                CurrUser.Name = txtName.Text;
                CurrUser.Password = txtPassword1.Text;
                CurrUser.IsAuthentication = chkIsAuth.Checked;
                CurrUser.PositionNo = ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbPosition.SelectedItem).StrValue;
                CurrUser.Status = cmbStatus.SelectedIndex==1;
                if (IsNew) //Шинэ
                {                    
                    res = reg.AddUser(CurrUser);
                    id = res.Code == 0 ? int.Parse(res.RetData.ToString()) : 0;
                    CurrUser.UserId=id;
                }
                else //Засах
                {
                    res = reg.EditUser(CurrUser);
                    id = CurrUser.UserId;                    
                }
                if (res.Code != 0)
                {
                    Globals.Err(res.Message);
                    return ;
                }

                res=reg.JoinRole(id,roles);
                if (res.Code != 0)
                    Globals.Err(res.Message);
                else
                {
                    Globals.Info(res.Message);
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
        }

        private void btnAddRole_Click(object sender, EventArgs e)
        {
            frmChooseRole frm=new frmChooseRole();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (lstRoles.Items.Cast<BranchOfSansar.Sansar.Enquiry.ComboItem>().Where(s=>s.IntValue==frm.SelectedRole.IntValue).Count()>0)
                {
                    Globals.Warr("Энэ эрх нэмэгдсэн байна!");
                    return;
                }
                lstRoles.Items.Add(frm.SelectedRole);
            }
        }

        private void btnDeleteRole_Click(object sender, EventArgs e)
        {
            if (lstRoles.SelectedIndex < 0)
            {
                Globals.Warr("Устгах өгөгдөл сонгогдоогүй байна!");
                return;
            }
            lstRoles.Items.RemoveAt(lstRoles.SelectedIndex);
        }

    }
}
